package com.sgb.merchant.view.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.IndustryCategoryEntity;
import com.sgb.link.entity.merchant.PublishIndustryEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivityPublishRequireBinding;
import com.sgb.merchant.viewmodel.PublishIndustryViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NumberUtil;
import com.swgk.core.util.PickerHelper;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 王彬臣
 * @date: 2021/10/14
 * @Description: 发布入驻要求
 */
@Route(path = PathMerchant.MerchantActivityPublishRequire)
public class MerchantActivityPublishRequire extends BaseActivity<PublishIndustryViewModel, MerchantActivityPublishRequireBinding> implements ItemInputTextView.OnWholeItemClickListener {
    @Autowired(name = RouterKey.DATA)
    PublishIndustryEntity mEntity;

    @Autowired(name = RouterKey.DATA1)
    ArrayList<String> logoList;

    @Autowired(name = RouterKey.DATA2)
    ArrayList<String> urlList;

    @Autowired(name = RouterKey.BOOLEAN, desc = "是否来着我的页面")
    boolean isSelf = false;

    boolean isPublish;

    List<IndustryCategoryEntity> mTypeData = new ArrayList<>();
    List<IndustryCategoryEntity> mTaxData = new ArrayList<>();
    private OptionsPickerView mQualificationPicker, mTaxPicker;

    List<File> fileEntities = new ArrayList<>();
    File logoFile;


    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_publish_require;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(PublishIndustryViewModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setOnClick(this);
        if (TextUtils.isEmpty(mEntity.getNo())) {
            isPublish = true;
        } else {
            mBinding.actionBar.setTitle("编辑产业园区");
            isPublish = false;
        }


        mBinding.actionBar.setOnBackClickListener(this);
        mBinding.itvTypes.setOnWholeItemClickListener(this);
        mBinding.itvTax.setOnWholeItemClickListener(this);
        mBinding.itvSize.setLabelRightMargin();
        mBinding.itvSize.setInfilterType(ItemInputTextView.TYPE_NUMBER_INTEGER);
        mBinding.itvCost.setInfilterType(ItemInputTextView.TYPE_NUMBER_DECIMAL);
        mBinding.itvCost.setCheck(10, 2, false);
        mBinding.itvCost.setLabelRightMargin();
        mBinding.itvTurnover.setInfilterType(ItemInputTextView.TYPE_NUMBER_DECIMAL);
        mBinding.itvTurnover.setCheck(10, 2, false);
        mBinding.itvTurnover.setLabelRightMargin();

        IndustryCategoryEntity data1 = new IndustryCategoryEntity("企业", "PQT1");
        IndustryCategoryEntity data2 = new IndustryCategoryEntity("组织", "PQT2");
        IndustryCategoryEntity data3 = new IndustryCategoryEntity("团队", "PQT3");
        IndustryCategoryEntity data4 = new IndustryCategoryEntity("个人", "PQT4");

        mTypeData.add(data1);
        mTypeData.add(data2);
        mTypeData.add(data3);
        mTypeData.add(data4);

        mQualificationPicker = PickerHelper.with(this).getCommonPicker("选择主体类型", mTypeData, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                IndustryCategoryEntity firstCategory = mTypeData.get(options1);
                mBinding.itvTypes.setContent(firstCategory.getCategoryName());
                mEntity.getImIndustrialParkQualificationsDTO().setQualificationTypes(firstCategory.getCategoryNo());
            }
        });

        IndustryCategoryEntity data5 = new IndustryCategoryEntity("正常报税", "TAX1");
        IndustryCategoryEntity data6 = new IndustryCategoryEntity("非正常报税", "TAX2");

        mTaxData.add(data5);
        mTaxData.add(data6);


        mTaxPicker = PickerHelper.with(this).getCommonPicker("选择税务情况", mTaxData, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                IndustryCategoryEntity firstCategory = mTaxData.get(options1);
                mBinding.itvTax.setContent(firstCategory.getCategoryName());
                mEntity.getImIndustrialParkQualificationsDTO().setTaxTypes(firstCategory.getCategoryNo());
            }
        });
        PublishIndustryEntity.ImIndustrialParkQualificationsDTOBean parkQualificationsDTOBean = mEntity.getImIndustrialParkQualificationsDTO();
        if (!TextUtils.isEmpty(mEntity.getImIndustrialParkQualificationsDTO().getQualificationTypes())) {
            for (IndustryCategoryEntity entity : mTypeData) {
                if (entity.getCategoryNo().equals(parkQualificationsDTOBean.getQualificationTypes())) {
                    mBinding.itvTypes.setContent(entity.getCategoryName());
                    break;
                }
            }
        }
        if (!TextUtils.isEmpty(mEntity.getImIndustrialParkQualificationsDTO().getTaxTypes())) {
            for (IndustryCategoryEntity entity : mTaxData) {
                if (entity.getCategoryNo().equals(parkQualificationsDTOBean.getTaxTypes())) {
                    mBinding.itvTax.setContent(entity.getCategoryName());
                    break;
                }
            }
        }
        if (!TextUtils.isEmpty(parkQualificationsDTOBean.getBusinessScope())) {
            mBinding.etArea.setEditContent(parkQualificationsDTOBean.getBusinessScope());
        }
        if (!TextUtils.isEmpty(parkQualificationsDTOBean.getCollaboratorQualifications())) {
            mBinding.etRequire.setEditContent(parkQualificationsDTOBean.getCollaboratorQualifications());
        }
        if (!TextUtils.isEmpty(parkQualificationsDTOBean.getLocateFee())) {
            mBinding.itvCost.setContent(NumberUtil.trim0(parkQualificationsDTOBean.getLocateFee()));
        }
        if (!TextUtils.isEmpty(parkQualificationsDTOBean.getRevenueYear())) {
            mBinding.itvTurnover.setContent(NumberUtil.trim0(parkQualificationsDTOBean.getRevenueYear()));
        }
        if (!TextUtils.isEmpty(parkQualificationsDTOBean.getQualificationVolume())) {
            mBinding.itvSize.setContent(NumberUtil.trim0(parkQualificationsDTOBean.getQualificationVolume()));
        }

        initData();
    }

    private void initData() {
        //筛选出需要上传的图片并标记位置
        for (int i = 0; i < urlList.size(); i++) {
            String url = urlList.get(i);
            if (!url.contains("http") || !url.contains("https")) {
                fileEntities.add(new File(url));
            }
        }
        //筛选出需要上传的图片并标记位置
        for (int i = 0; i < logoList.size(); i++) {
            String url = logoList.get(i);
            if (!url.contains("http") || !url.contains("https")) {
                logoFile = (new File(url));
            }
        }
        mViewModel.ldUrl.observe(this, url -> {
            mEntity.setParkLogo(url);
            DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
            if (fileEntities.size() > 0) {
                mViewModel.uploadMutiFileModel(fileEntities);
            } else {
                mViewModel.editPark(mEntity);
            }
        });
        mViewModel.uploadUrls.observe(this, urlList -> {
            mEntity.getParkImages().addAll(urlList);
            DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
            mViewModel.editPark(mEntity);
        });
        mViewModel.ldResult.observe(this, result -> {
            if (result) {

                //刷新详情页
                EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_DETAIL));
                if (isPublish) {
                    MToast.showToast(this, "发布成功");
                } else {
                    MToast.showToast(this, "编辑成功");
                }
                if (isSelf) {
                    ARouter.getInstance().build(PathMerchant.SelfIndustryListActivity).navigation();
                } else {
                    //刷新列表页
                    EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH));
                }
                setResult(RESULT_OK);
                finish();

            }
        });
        mViewModel.ldState.observe(this, result -> {
            if (result) {
                DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
                if (logoFile != null) {
                    mViewModel.uploadFile(logoFile);
                } else if (fileEntities.size() != 0) {
                    mViewModel.uploadMutiFileModel(fileEntities);
                } else {
                    mViewModel.editPark(mEntity);
                }
            } else {
                new RoundDialog.Builder(this)
                        .title("温馨提示")
                        .content("该数据状态已发生变化，请刷新后再进行操作。")
                        .confirm("知道了")
                        .singleBtn(true)
                        .cancelable(false)
                        .confirmCallback(v -> {
                            //刷新列表页
                            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_REFRESH));
                            //关闭详情页
                            EventBus.getDefault().post(MainEvent.make().setMessageTag(EventConstant.EVENT_MERCHANT_SELF_INDUSTRY_DETAIL_FINISH));
                            setResult(RESULT_OK);
                            finish();
                        })
                        .show();

            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == R.id.iv_back_red) {
            finish();
        } else if (id == R.id.tv_last_page) {
            Intent intent = new Intent();
            intent.putExtra("info", mEntity);
            setResult(RESULT_OK, intent);
            finish();
        } else if (id == R.id.tv_commit) {
            if (ClickUtils.isDoubleClick()) {
                return;
            }
            String type = mBinding.itvTypes.getContent();
            String size = mBinding.itvSize.getContent();
            String tax = mBinding.itvTax.getContent();
            String turnover = mBinding.itvTurnover.getContent();
            String cost = mBinding.itvCost.getContent();
            String area = mBinding.etArea.getEditContent();
            String require = mBinding.etRequire.getEditContent();

            if (TextUtils.isEmpty(type)) {
                MToast.showToast(this, "请选择主体类型！");
                return;
            }
            if (TextUtils.isEmpty(size)) {
                MToast.showToast(this, "请输入主体规模！");
                return;
            }
            if (TextUtils.isEmpty(tax)) {
                MToast.showToast(this, "请选择税务情况！");
                return;
            }
            if (TextUtils.isEmpty(turnover)) {
                MToast.showToast(this, "请输入年营业额！");
                return;
            }
            if (TextUtils.isEmpty(cost)) {
                MToast.showToast(this, "请输入入驻费用！");
                return;
            }


            mEntity.getImIndustrialParkQualificationsDTO().setRevenueYear(turnover);
            mEntity.getImIndustrialParkQualificationsDTO().setQualificationVolume(size);
            mEntity.getImIndustrialParkQualificationsDTO().setLocateFee(cost);
            if (!TextUtils.isEmpty(area)) {
                mEntity.getImIndustrialParkQualificationsDTO().setBusinessScope(area);
            } else {
                mEntity.getImIndustrialParkQualificationsDTO().setBusinessScope("");
            }
            if (!TextUtils.isEmpty(require)) {
                mEntity.getImIndustrialParkQualificationsDTO().setCollaboratorQualifications(require);
            } else {
                mEntity.getImIndustrialParkQualificationsDTO().setCollaboratorQualifications("");
            }
            DialogHelper.showProgressDialog(this, "").setCanceledOnTouchOutside(false);
            if (isPublish) {
                if (logoFile != null) {
                    mViewModel.uploadFile(logoFile);
                } else if (fileEntities.size() != 0) {
                    mViewModel.uploadMutiFileModel(fileEntities);
                } else {
                    mViewModel.editPark(mEntity);
                }
            } else {
                mViewModel.getCurrentState(mEntity.getNo());
            }
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.itv_types) {
            mQualificationPicker.show();
        } else if (id == R.id.itv_tax) {
            mTaxPicker.show();
        }

    }
}
